#include "bsp_usart.h"
#include "cmsis_os.h"

extern osThreadId comm_taskHandle;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;

static void huart_double_buf_init(Usart_handle* usart_handle){
     __HAL_UART_ENABLE_IT(usart_handle->huart_use,UART_IT_IDLE);
    HAL_UART_Receive_DMA(usart_handle->huart_use,usart_handle->recv_buf[0],256);
}


void usart_init(Usart_handle* usart_handle, UART_HandleTypeDef* huart_use, uint8_t id, bool tx_use_dma_if){
    usart_handle->huart_id = id;
    usart_handle->huart_use = huart_use;
    usart_handle->init_if = true;
    usart_handle->tx_dma_if = tx_use_dma_if;
    huart_double_buf_init(usart_handle);
}



void usart_callback(Usart_handle* usart_handle){
    if(RESET!=__HAL_UART_GET_FLAG(usart_handle->huart_use,UART_FLAG_IDLE)){
			__HAL_UART_CLEAR_IDLEFLAG(usart_handle->huart_use);
			HAL_UART_DMAStop(usart_handle->huart_use);
			uint16_t data_len = 0;
			data_len = 256 - usart_handle->huart_use->hdmarx->Instance->NDTR;
			usart_rx_isr_handle(usart_handle, usart_handle->now_recv_buf_id, data_len);
			usart_handle->now_recv_buf_id++;
			usart_handle->now_recv_buf_id %= 2;
			HAL_UART_Receive_DMA(usart_handle->huart_use,usart_handle->recv_buf[usart_handle->now_recv_buf_id],256);
		}
}

void usart_rx_isr_handle(Usart_handle* usart_handle, uint8_t use_buf_id, uint16_t recv_len){
    Cmd_Message_pack temp = {
            .data_from = USART,
            .data_length = recv_len
    };
    memcpy(&temp.message_in[0], &usart_handle->recv_buf[use_buf_id][0], (size_t)recv_len);
    message_queue_put(temp);
    temp.avilable = true;
    osThreadResume(comm_taskHandle);
}

void huart_send(Usart_handle* usart_handle, uint8_t* tx_buf, uint16_t data_len){
    if(usart_handle->tx_dma_if){
        HAL_UART_Transmit_DMA(usart_handle->huart_use, tx_buf, data_len);
    }else{
        HAL_UART_Transmit(usart_handle->huart_use, tx_buf, data_len, 0xFF);
    }
}
